'use strict';

/**
 * 根据通知类型获取分类的辅助函数
 * @param {string} type - 通知类型
 * @returns {string} 通知分类
 */
function getCategoryByType(type) {
  const typeMap = {
    'match_publish': '比赛通知',
    'match_review': '审核通知',
    'match_invitation': '比赛通知',
    'invitation_response': '比赛通知',
    'credential_update': '认证通知',
    'certificate_update': '认证通知', 
    'referee_evaluation': '执裁通知',
    'system': '系统通知'
  };
  return typeMap[type] || '系统通知';
}

// 云对象名：notification-service
module.exports = {
  /**
   * 发送通知
   * @param {object} params - 通知参数
   * @param {string} params.userId - 接收用户ID
   * @param {string} params.type - 通知类型
   * @param {string} params.category - 通知分类
   * @param {string} params.title - 通知标题
   * @param {string} params.content - 通知内容
   * @param {string} params.relatedId - 关联业务ID
   * @param {string} params.senderId - 发送者ID
   * @param {object} params.extraData - 扩展数据
   * @returns {object} 发送结果
   */
  async sendNotification(params) {
    try {
      const db = uniCloud.database();
      const { userId, type, category, title, content, relatedId, senderId, extraData } = params;
      
      if (!userId || !type || !title || !content) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      const notificationData = {
        user_id: userId,
        type: type,
        category: category || getCategoryByType(type),
        title: title,
        content: content,
        related_id: relatedId,
        sender_id: senderId,
        extra_data: extraData || {},
        is_read: false
        // create_time 由数据库自动生成，不需要手动设置
      };
      
      const result = await db.collection('user_notifications').add(notificationData);
      
      return {
        code: 0,
        message: '通知发送成功',
        data: {
          notificationId: result.id
        }
      };
    } catch (error) {
      console.error('发送通知失败:', error);
      return {
        code: -1,
        message: '发送通知失败: ' + error.message
      };
    }
  },

  /**
   * 批量发送通知
   * @param {object} params - 批量通知参数
   * @param {array} params.userIds - 接收用户ID数组
   * @param {string} params.type - 通知类型
   * @param {string} params.category - 通知分类
   * @param {string} params.title - 通知标题
   * @param {string} params.content - 通知内容
   * @param {string} params.relatedId - 关联业务ID
   * @param {string} params.senderId - 发送者ID
   * @param {object} params.extraData - 扩展数据
   * @returns {object} 发送结果
   */
  async batchSendNotification(params) {
    try {
      const db = uniCloud.database();
      const { userIds, type, category, title, content, relatedId, senderId, extraData } = params;
      
      if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
        return {
          code: -1,
          message: '用户ID列表不能为空'
        };
      }
      
      if (!type || !title || !content) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      const notifications = userIds.map(userId => ({
        user_id: userId,
        type: type,
        category: category || getCategoryByType(type),
        title: title,
        content: content,
        related_id: relatedId,
        sender_id: senderId,
        extra_data: extraData || {},
        is_read: false
        // create_time 由数据库自动生成，不需要手动设置
      }));
      
      // 分批发送，避免单次操作数据过多
      const batchSize = 100;
      const results = [];
      
      for (let i = 0; i < notifications.length; i += batchSize) {
        const batch = notifications.slice(i, i + batchSize);
        const result = await db.collection('user_notifications').add(batch);
        results.push(result);
      }
      
      return {
        code: 0,
        message: `批量发送通知成功，共发送${userIds.length}条`,
        data: {
          totalCount: userIds.length,
          results: results
        }
      };
    } catch (error) {
      console.error('批量发送通知失败:', error);
      return {
        code: -1,
        message: '批量发送通知失败: ' + error.message
      };
    }
  },

  /**
   * 获取用户通知列表
   * @param {string} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} readStatus - 读取状态筛选：all-全部, read-已读, unread-未读
   * @returns {object} 通知列表
   */
  async getNotifications(userId, page = 1, limit = 10, readStatus = 'all') {
    try {
      const db = uniCloud.database();
      
      if (!userId) {
        return {
          code: -1,
          message: '用户ID不能为空'
        };
      }
      
      const pageNum = parseInt(page) || 1;
      const limitNum = parseInt(limit) || 10;
      const skip = (pageNum - 1) * limitNum;
      
      // 构建查询条件
      const where = {
        user_id: userId
      };
      
      // 根据读取状态筛选
      if (readStatus === 'read') {
        where.is_read = true;
      } else if (readStatus === 'unread') {
        where.is_read = false;
      }
      
      // 查询总数
      const countResult = await db.collection('user_notifications').where(where).count();
      const total = countResult.total;
      
      // 查询通知列表 - 使用多字段排序确保新消息在前
      const notificationsResult = await db.collection('user_notifications')
        .where(where)
        .orderBy('create_time', 'desc')
        .orderBy('_id', 'desc')
        .skip(skip)
        .limit(limitNum)
        .get();
      
      return {
        code: 0,
        message: '获取通知列表成功',
        data: notificationsResult.data,
        total,
        page: pageNum,
        limit: limitNum,
        pages: Math.ceil(total / limitNum)
      };
    } catch (error) {
      console.error('获取通知列表失败:', error);
      return {
        code: -1,
        message: '获取通知列表失败: ' + error.message
      };
    }
  },

  /**
   * 获取用户未读通知数量
   * @param {string} userId - 用户ID
   * @returns {object} 未读数量
   */
  async getUnreadCount(userId) {
    try {
      const db = uniCloud.database();
      
      if (!userId) {
        return {
          code: -1,
          message: '用户ID不能为空'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          user_id: userId,
          is_read: false
        })
        .count();
      
      return {
        code: 0,
        message: '获取未读数量成功',
        data: {
          unreadCount: result.total
        }
      };
    } catch (error) {
      console.error('获取未读数量失败:', error);
      return {
        code: -1,
        message: '获取未读数量失败: ' + error.message
      };
    }
  },

  /**
   * 标记通知为已读
   * @param {string} notificationId - 通知ID
   * @param {string} userId - 用户ID
   * @returns {object} 操作结果
   */
  async markAsRead(notificationId, userId) {
    try {
      const db = uniCloud.database();
      
      if (!notificationId || !userId) {
        return {
          code: -1,
          message: '参数不能为空'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          _id: notificationId,
          user_id: userId
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      if (result.updated === 0) {
        return {
          code: -1,
          message: '通知不存在或无权操作'
        };
      }
      
      return {
        code: 0,
        message: '标记已读成功'
      };
    } catch (error) {
      console.error('标记已读失败:', error);
      return {
        code: -1,
        message: '标记已读失败: ' + error.message
      };
    }
  },

  /**
   * 批量标记已读
   * @param {array} notificationIds - 通知ID数组
   * @param {string} userId - 用户ID
   * @returns {object} 操作结果
   */
  async batchMarkAsRead(notificationIds, userId) {
    try {
      const db = uniCloud.database();
      
      if (!notificationIds || !Array.isArray(notificationIds) || !userId) {
        return {
          code: -1,
          message: '参数不正确'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          _id: db.command.in(notificationIds),
          user_id: userId
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      return {
        code: 0,
        message: `批量标记已读成功，共${result.updated}条`,
        data: {
          updatedCount: result.updated
        }
      };
    } catch (error) {
      console.error('批量标记已读失败:', error);
      return {
        code: -1,
        message: '批量标记已读失败: ' + error.message
      };
    }
  },

  /**
   * 全部标记为已读
   * @param {string} userId - 用户ID
   * @returns {object} 操作结果
   */
  async markAllAsRead(userId) {
    try {
      const db = uniCloud.database();
      
      if (!userId) {
        return {
          code: -1,
          message: '用户ID不能为空'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          user_id: userId,
          is_read: false
        })
        .update({
          is_read: true,
          read_time: new Date()
        });
      
      return {
        code: 0,
        message: `全部标记已读成功，共${result.updated}条`,
        data: {
          updatedCount: result.updated
        }
      };
    } catch (error) {
      console.error('全部标记已读失败:', error);
      return {
        code: -1,
        message: '全部标记已读失败: ' + error.message
      };
    }
  },

  /**
   * 删除通知
   * @param {string} notificationId - 通知ID
   * @param {string} userId - 用户ID
   * @returns {object} 操作结果
   */
  async deleteNotification(notificationId, userId) {
    try {
      const db = uniCloud.database();
      
      if (!notificationId || !userId) {
        return {
          code: -1,
          message: '参数不能为空'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          _id: notificationId,
          user_id: userId
        })
        .remove();
      
      if (result.deleted === 0) {
        return {
          code: -1,
          message: '通知不存在或无权操作'
        };
      }
      
      return {
        code: 0,
        message: '删除通知成功'
      };
    } catch (error) {
      console.error('删除通知失败:', error);
      return {
        code: -1,
        message: '删除通知失败: ' + error.message
      };
    }
  },

  /**
   * 批量删除通知
   * @param {array} notificationIds - 通知ID数组
   * @param {string} userId - 用户ID
   * @returns {object} 操作结果
   */
  async batchDeleteNotifications(notificationIds, userId) {
    try {
      const db = uniCloud.database();
      
      if (!notificationIds || !Array.isArray(notificationIds) || notificationIds.length === 0 || !userId) {
        return {
          code: -1,
          message: '参数不正确'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          _id: db.command.in(notificationIds),
          user_id: userId
        })
        .remove();
      
      return {
        code: 0,
        message: `批量删除通知成功，共删除${result.deleted}条`,
        data: {
          deletedCount: result.deleted
        }
      };
    } catch (error) {
      console.error('批量删除通知失败:', error);
      return {
        code: -1,
        message: '批量删除通知失败: ' + error.message
      };
    }
  },

  /**
   * 获取通知详情
   * @param {string} notificationId - 通知ID
   * @param {string} userId - 用户ID
   * @returns {object} 通知详情
   */
  async getNotificationDetail(notificationId, userId) {
    try {
      const db = uniCloud.database();
      
      if (!notificationId || !userId) {
        return {
          code: -1,
          message: '参数不能为空'
        };
      }
      
      const result = await db.collection('user_notifications')
        .where({
          _id: notificationId,
          user_id: userId
        })
        .get();
      
      if (!result.data || result.data.length === 0) {
        return {
          code: -1,
          message: '通知不存在'
        };
      }
      
      // 如果是未读状态，自动标记为已读
      const notification = result.data[0];
      if (!notification.is_read) {
        // 直接更新数据库，避免this上下文问题
        await db.collection('user_notifications')
          .where({
            _id: notificationId,
            user_id: userId
          })
          .update({
            is_read: true,
            read_time: new Date()
          });
        notification.is_read = true;
        notification.read_time = new Date();
      }
      
      return {
        code: 0,
        message: '获取通知详情成功',
        data: notification
      };
    } catch (error) {
      console.error('获取通知详情失败:', error);
      return {
        code: -1,
        message: '获取通知详情失败: ' + error.message
      };
    }
  },

}; 